<template>
    <ElTree ref="myTree" v-bind="commProps" :data="props.data" class="my-tree" @current-change="nodeChange">
        <template #default="{ node, data }">
            <div class="my-tree-item flex">
                <div :style="{ backgroundColor: extendProps.levelColors[node.level - 1] }" class="my-tree-item-level">{{ `lv${node.level}` }}</div>
                <div class="my-tree-item-label">{{ node.label || data.name }}</div>
            </div>
        </template>
    </ElTree>
</template>

<script setup lang="ts">
import type { TreeInstance } from 'element-plus';
import type { ProductTreeDefineProps, IProductTreeInstance, ProductTreeDefineEmits } from './props';
const props = withDefaults(defineProps<ProductTreeDefineProps>(), {
    data() {
        return [];
    },
});

const emits = defineEmits<ProductTreeDefineEmits>();

const defaultExtends = {
    levelColors: ['#94DF58', '#F5D530', '#F88D3F'],
};

const extendProps = computed(() => {
    return { ...defaultExtends, ...props.extends };
});

const defaultProps: ProductTreeDefineProps['props'] = {
    nodeKey: 'id',
};

const commProps = computed(() => {
    return { ...defaultProps, ...props.props };
});

const myTree = ref<TreeInstance>();

const filter = (value: string) => {
    myTree.value?.filter(value);
};

const setCurrentKey = (key: string, shouldAutoExpandParent: boolean = true) => {
    myTree.value?.setCurrentKey(key, shouldAutoExpandParent);
};

const nodeChange = (data: any, node: any) => {
    emits('select', data, node);
};

defineExpose<IProductTreeInstance>({
    filter,
    setCurrentKey,
});
</script>

<style scoped>
.my-tree-item {
    height: 32px;
    align-items: center;
    gap: 12px;
}
.my-tree-item-level {
    font-size: 10px;
    color: #e6ffffff;
    line-height: 14px;
    height: 14px;
    padding: 0px 6px;
    border-radius: 2px;
}
.my-tree-item-label {
    font-size: 12px;
}
</style>
